<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 头部部分 -->
      <PageTools :show-before="true">
        <template #before>一共{{ page.total }}条数据</template>
        <template #after>
          <el-button size="small" type="warning" @click="$router.push('/import')">导进</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 内容部分 -->
      <el-card>
        <el-table v-loading="loading" border :data="employeeList">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="头像" width="200">
            <template #default="{row}">
              <img v-imgerr="require('@/assets/common/head.jpg')" :src="row.staffPhoto" class="avatar" alt="" @click="toggleQRCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            sortable=""
            :formatter="formatFormEmployment"
          />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              <!-- 用的是管道符过滤时间 -->
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template #default="{row}">
              <!-- element UI 默认绑定是一个 v-model 双向绑定 -->
              <!-- 其实是 :value 和 @input 的结合简化语法糖
              这里只需要 data 数据渲染即可, 无需交互(@input) -->
              <el-switch
                :value="row.enableState === 1"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next, sizes, total"
            :total="page.total"
            :page-size="page.size"
            :page-sizes="[5, 10, 15, 20]"
            @current-change="currentChange"
            @size-change="sizeChange"
          />
        </el-row>
      </el-card>
      <AddEmployee :show-dialog="showDialog" />
      <AssignRole ref="assignRole" :show-dialog.sync="showRoles" :user-id="userId" />
      <el-dialog title="二维码" :visible="showQRCode" @close="showQRCode=false">
        <el-row type="flex" justify="center">
          <!-- 放入二维码 -->
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// import PageTools from '@/components/PageTools/index.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EnumEmployee from '@/api/constant/employees'
import { formatDate } from '@/filters'
import AddEmployee from './components/add-employee.vue'
import QRCode from 'qrcode'
import AssignRole from './components/assign-role.vue'

export default {
  components: {
    AddEmployee, AssignRole
  },
  data() {
    return {
      employeeList: [],
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      loading: false,
      showDialog: false,
      showQRCode: false,
      showRoles: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 获取全部员工信息
    async getEmployeeList() {
      // 加载没完成之前显示转转菊花图
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page)
      this.employeeList = rows
      this.page.total = total
      console.log(this.employeeList)
      this.loading = false
    },
    // 监听分页切换
    currentChange(newPage) {
      // 参数就是记录切换到的页码
      this.page.page = newPage
      // 重新发请求
      this.getEmployeeList()
    },
    // 监听分页点击最大条数
    sizeChange(newPage) {
      this.page.size = newPage
      // 重新发请求
      this.getEmployeeList()
    },
    // 员工聘用形式（格式化，枚举）
    formatFormEmployment(row, col, cellValue) {
      // 普通做法
      // const hireType = [
      //   { id: 1, value: '正式员工' },
      //   { id: 2, value: '非正式' },
      //   { id: 3, value: '临时工' },
      //   { id: 4, value: '实习生' },
      //   { id: 4, value: '关系户' }
      // ]
      // find是寻找符合条件的，并返回符合条件的
      // obj存了id(cellValue原数据的格子，这里的原数据存的是1或者2，根据id对应的格子进行命名)
      const obj = EnumEmployee.hireType.find(item => item.id === Number(cellValue))
      return obj ? obj.value : '未知'
    },
    async exportExcel() {
      // 1.导出需要用到花裤衩的封装
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      // export_json_to_excel({
      //   基本数据
      //   header: ['姓名', '年龄', '性别'],
      //   data: [
      //     // { 姓名: 'tom', 年龄: 666, 性别: '小姐姐' }
      //     ['tom', 666, '小姐姐'],
      //     ['rose', 66, '小哥哥'],
      //     ['jerry', 12, '小姐姐']
      //   ]
      // })
      // 2.获取所有员工数据(数据库太多，导出99条即可)
      const { rows } = await getEmployeeList({ page: 1, size: 99 })
      console.log(rows)
      // 3.根据插件需求转换数据
      const dict = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const header = Object.keys(dict)
      console.log(header)

      const data = rows.map(user => {
        return this.obj2arr(user, dict)
      })
      console.log(data)

      // 4.生成excel
      export_json_to_excel({
        header,
        data
      })
    },
    obj2arr(user, dict) {
      const userArr = []
      for (const key in dict) {
        const enKey = dict[key]
        let value = user[enKey]
        // 有三个数据应该特殊处理
        // 入职日期, 聘用形式, 转正日期
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          value = formatDate(value)
        }
        if (enKey === 'formOfEmployment') {
          const obj = EnumEmployee.hireType.find(item => item.id === value)
          value = obj ? obj.value : '未知形式'
        }
        userArr.push(value)
      }
      return userArr
    },
    async delEmployee(id) {
      // 二次确认
      await this.$confirm('是否确认删除当前员工')
      // 发请求
      await delEmployee(id)
      // 如果发现当前页不是第一页而且只剩下最后一条, 往前翻页
      if (this.employeeList.length === 1 && this.page.page > 1) {
        this.page.page--
      }
      // 提醒用户
      this.$message.success('删除成功')
      // 更新页面
      this.getEmployeeList()
    },
    // 点击头像显示二维码
    toggleQRCode(url) {
      // 如果图片有 弹窗就出来
      if (url) {
        this.showQRCode = true
        // dom渲染完成就生成二维码
        this.$nextTick(() => {
          console.log(this.$refs.myCanvas)
          QRCode.toCanvas(this.$refs.myCanvas, url, {
            // 额外可选参数, 控制二维码颜色
            width: 200,
            color: {
              dark: '#5081fc'
            }
          })
        })
      }
    },
    assignRole(id) {
      this.userId = id
      // 用refs方式把id传给子组件
      this.$refs.assignRole.getUserDetailById(id)
      this.showRoles = true
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 90%;
  height: 130px;
  object-fit: cover;
  border-radius: 10px;
}
</style>
